import { useState } from 'react';
import { Link } from 'react-router-dom';
import { ImageInfo } from '@/types';
import { cn } from '@/lib/utils';
import { motion } from 'framer-motion';

interface ImageThumbnailProps {
  image: ImageInfo;
}

/**
 * 图片缩略图组件
 * 展示图片缩略图和标题，点击可进入详情页
 */
export default function ImageThumbnail({ image }: ImageThumbnailProps) {
  const [isLoading, setIsLoading] = useState(true);
  const [hasError, setHasError] = useState(false);

  const handleImageLoad = () => {
    setIsLoading(false);
  };

  const handleImageError = () => {
    setIsLoading(false);
    setHasError(true);
  };

  return (
    <motion.div 
      className="group"
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.3 }}
    >
      <Link to={`/detail/${image.id}`} className="block">
        <div className="relative overflow-hidden rounded-xl bg-white shadow-md transition-all duration-300 hover:shadow-xl">
          {/* 图片容器 */}
          <div className="aspect-video w-full overflow-hidden bg-gray-100">
            {isLoading && (
              <div className="flex h-full w-full items-center justify-center bg-gray-100">
                <i className="fa-solid fa-circle-notch fa-spin text-gray-400 text-2xl"></i>
              </div>
            )}
            
            {hasError ? (
              <div className="flex h-full w-full items-center justify-center bg-gray-100 text-gray-400">
                <i className="fa-solid fa-image text-4xl"></i>
              </div>
            ) : (
              <img
                src={image.imageUrl}
                alt={image.title}
                onLoad={handleImageLoad}
                onError={handleImageError}
                className={cn(
                  "h-full w-full object-cover transition-transform duration-500",
                  isLoading ? "opacity-0" : "opacity-100",
                  "group-hover:scale-105"
                )}
              />
            )}
          </div>
          
          {/* 标题区域 */}
          <div className="p-4">
            <h3 className="text-lg font-semibold text-gray-800 transition-colors group-hover:text-blue-600">
              {image.title}
            </h3>
            <div className="mt-2 flex items-center text-sm text-gray-500 opacity-0 transition-opacity duration-300 group-hover:opacity-100">
              <i className="fa-solid fa-arrow-right mr-1"></i>
              <span>查看详情</span>
            </div>
          </div>
        </div>
      </Link>
    </motion.div>
  );
}